<script>
import {createProps, isEmpty} from '@/utils';
import {notification} from 'ant-design-vue';

export default {
  name: 'FieldComponentDelegate',
  props: {
    field: createProps(Object, () => ({})),
    fieldComponentRegistry: createProps(Object, () => ({})),
  },
  data() {
    return {
      value: undefined,
      title: undefined
    };
  },
  render(h) {
    return this.field
        && this.field.component
        && this.fieldComponentRegistry[this.field.component]
        && this.doRenderComponent(h) || undefined;
  },
  methods: {
    getFieldData() {
      if (isEmpty(this.value)) {
        notification.warn({message: '请录入字段值'});
        return;
      }
      return {
        variableName: this.value,
        variableTitle: this.title || this.value,
        variableType: this.field.variableType
      };
    },
    getProps() {
      return this.field.componentProps || {};
    },
    doRenderComponent(h) {
      return h(this.fieldComponentRegistry[this.field.component], {
        props: {
          ...this.getProps(),
          value: this.value,
          title: this.title,
        },
        on: {
          change: value => this.value = value,
          changeTitle: title => this.title = title,
          'update:value': value => this.value = value,
          'update:title': title => this.title = title,
        }
      });
    },
  },
};
</script>